/**
 * Created by lizhihang
 */

'use strict';
var express = require('express');
var router = express.Router();
var logger = require('../logger');
var superagent = require('superagent');
var jwt = require('jsonwebtoken');
var mongo = require('mongoskin');
const uuidV4 = require('uuid/v4');

var db = mongo.db("mongodb://localhost:27017/weGDUT");
db.bind('weGDUT');
/**
 * Test Login
 *
 */
function send(req, res, next) {
    var token = req.body.token
    var content = req.body.content
    var imgUrl = req.body.imgUrl
    var phone = req.body.phone
    console.log('imgurl' + imgUrl)
    if (token && content) {
        //尝试是否可以解析token，如果是格式正确的token，允许查找数据库，并且继续搜索教务系统
        try {
            let decoded = jwt.verify(token, 'thefirstminappofvtmer');
            console.log(decoded)
            let openid = decoded.openid;
            //查找数据库中是否已经绑定

            var result = new Promise((resolve, reject) => {
                db.weGDUT.find({ openid: openid }).toArray(function (err, items) {
                    resolve(items)
                })
            })
            var users;
            result.then(function (value) {
                users = value[0]
                if (!users) {
                    res.send({ code: 505, message: 'No this user' })
                } else {
                    //找到该用户
                    //准备插入数据库
                    let monent = {}
                    monent.uuid = uuidV4()              //唯一id
                    monent.openid = users.openid
                    if(req.body.name){
												if(req.body.name=="WeGDUT开发者"){
																monent.nickName = "WeGDUT开发者"
																monent.avatarUrl =  "http://image.yoricklee.com/WeGDUT/logo.jpg"
												} else{
																monent.nickName = req.body.name
																monent.avatarUrl =  "http://oox3shbsf.bkt.clouddn.com/avar.png"
												}
                    }else{
                        monent.nickName = users.nickName     //昵称                    
                        monent.avatarUrl = users.avatarUrl                    
                    }
                    monent.content = content             //内容
                    monent.imgUrl = imgUrl
                    monent.commentCount = 0              //评论数量
                    monent.likeCount = 0                //点赞数量
                    monent.phone = phone                //手机型号
                    let d = new Date()
                    monent.created_time = d.getTime()
                    //插入数据库

                    var db = mongo.db("mongodb://localhost:27017/monents");
                    db.bind('monents');
                    db.monents.insert(monent)
                    res.send({ code: 200, message: 'ok,sent' })
                }
            })

        } catch (err) {
            res.send({ code: 401, message: 'token invid' })
        }
    } else {
        res.send({ code: 402, message: 'token or content is required' })
    }
}

function getAllMonents(req, res, next) {
        var token = req.body.token
				var limit = req.param("limit",10)
				var currentPage = req.param("currentPage",1)
				if(currentPage < 1){
								currentPage = 1;
				}
        console.log('allmonent:'+token)
        if(token){
            //尝试是否可以解析token，如果是格式正确的token，允许查找数据库，并且继续搜索教务系统
            try {
                let decoded = jwt.verify(token, 'thefirstminappofvtmer');
                console.log(decoded)
                let openid = decoded.openid;
                //查找数据库中是否已经绑定

                var result = new Promise((resolve, reject) => {
                    db.weGDUT.find({ openid: openid }).toArray(function (err, items) {
                        resolve(items)
                    })
                })
                var users;
                result.then(function (value) {
                    users = value[0]
                    if (!users) {
                        res.send({ code: 505, message: 'No this user' })
                    }else {

                        var db = mongo.db("mongodb://localhost:27017/monents");
                        db.bind('monents');
                        var monentsRes = new Promise((resolve, reject) => {
                            db.monents.find().sort( { created_time: -1 } ).toArray(function (err, items) {
                                resolve(items)
                            })
                        })
                        monentsRes.then(function (value) {
												    console.log('gdutWalltest:'+res.length);
                            res.send({ code: 200, message: 'ok', data:value })
                        }), function (err) {
                            res.send({ code: 501, message: 'mongo DB error' })
                        }

                    }
                })
            } catch (err) {
                res.send({ code: 401, message: 'token invid' })
            }
        }else{
            res.send({ code: 500, message: 'token is required' })
        }
    } 

function getPersonMonents(req, res, next) {
        var token = req.body.token
        console.log('allmonent:'+token)
        if(token){
            //尝试是否可以解析token，如果是格式正确的token，允许查找数据库，并且继续搜索教务系统
            try {
                let decoded = jwt.verify(token, 'thefirstminappofvtmer');
                console.log(decoded)
                let openid = decoded.openid;
                //查找数据库中是否已经绑定

                var result = new Promise((resolve, reject) => {
                    db.weGDUT.find({ openid: openid }).toArray(function (err, items) {
                        resolve(items)
                    })
                })
                var users;
                result.then(function (value) {
                    users = value[0]
                    if (!users) {
                        res.send({ code: 505, message: 'No this user' })
                    }else {

                        var db = mongo.db("mongodb://localhost:27017/monents");
                        db.bind('monents');
                        var monentsRes = new Promise((resolve, reject) => {
                            db.monents.find({openid:users.openid}).toArray(function (err, items) {
                                resolve(items)
                            })
                        })
                        monentsRes.then(function (value) {
                            res.send({ code: 200, message: 'ok', data:value })
                        }), function (err) {
                            res.send({ code: 501, message: 'mongo DB error' })
                        }

                    }
                })
            } catch (err) {
                res.send({ code: 401, message: 'token invid' })
            }
        }else{
            res.send({ code: 500, message: 'token is required' })
        }
    } 

function sendComment(req, res, next) {
    var token = req.body.token
    var content = req.body.content
    var uuid = req.body.uuid

    console.log('content' + uuid)
    if (token && content && uuid) {
        //尝试是否可以解析token，如果是格式正确的token，允许查找数据库，并且继续搜索教务系统
        try {
            let decoded = jwt.verify(token, 'thefirstminappofvtmer');
            console.log(decoded)
            let openid = decoded.openid;
            //查找数据库中是否已经绑定

            var result = new Promise((resolve, reject) => {
                db.weGDUT.find({ openid: openid }).toArray(function (err, items) {
                    resolve(items)
                })
            })
            var users;
            result.then(function (value) {
                users = value[0]
                if (!users) {
                    res.send({ code: 505, message: 'No this user' })
                } else {
                    //找到该用户
                    //准备插入数据库
                    let comment = {}
                    comment.uuid = uuid
                    if(req.body.name){
												if(req.body.name=="WeGDUT开发者"){
																comment.nickname = "WeGDUT开发者"
																comment.avatarUrl =  "http://image.yoricklee.com/WeGDUT/logo.jpg"
												} else{
																comment.nickname = req.body.name
																comment.avatarUrl = "http://oox3shbsf.bkt.clouddn.com/avar.png"
												}
                    }else{
                        comment.nickname = users.nickName
                        comment.avatarUrl = users.avatarUrl
                    }
                    
                    comment.content = content
                    let d = new Date()
                    comment.created_time = d.getTime()
                    //插入数据库

                    var db = mongo.db("mongodb://localhost:27017/comments");
                    db.bind('comments');
                    db.comments.insert(comment)

                    db = mongo.db("mongodb://localhost:27017/monents");
                    db.bind('monents');
                    db.monents.update({ uuid: uuid }, { $inc: { commentCount: 1 } })

                    res.send({ code: 200, message: 'ok,sent comment succeed' })
                }
            })

        } catch (err) {
            res.send({ code: 401, message: 'token invid' })
        }
    } else {
        res.send({ code: 402, message: 'token or uuid or content is required' })
    }
}

function like(req, res, next) {
    var token = req.body.token
    var uuid = req.body.uuid

    console.log('content' + uuid)
    if (token && uuid) {
        //尝试是否可以解析token，如果是格式正确的token，允许查找数据库，并且继续搜索教务系统
        try {
            let decoded = jwt.verify(token, 'thefirstminappofvtmer');
            console.log(decoded)
            let openid = decoded.openid;
            //查找数据库中是否已经绑定
            var db = mongo.db("mongodb://localhost:27017/weGDUT");
            db.bind('weGDUT');
            var result = new Promise((resolve, reject) => {
                db.weGDUT.find({ openid: openid }).toArray(function (err, items) {
                    resolve(items)
                })
            })
            var users;
            result.then(function (value) {
                users = value[0]
                if (!users) {
                    res.send({ code: 505, message: 'No this user' })
                } else {
                    //找到该用户
                    //准备插入数据库
                    db = mongo.db("mongodb://localhost:27017/monents");
                    db.bind('monents');
                    db.monents.update({ uuid: uuid }, { $inc: { likeCount: 1 } })

                    res.send({ code: 200, message: 'ok,liked' })
                }
            })
        } catch (err) {
            res.send({ code: 401, message: 'token invid' })
        }
    } else {
        res.send({ code: 402, message: 'token or uuid is required' })
    }
}


function detail(req, res, next) {
    var token = req.body.token
    var uuid = req.body.uuid

    console.log('content' + uuid)
    if (token && uuid) {
        //尝试是否可以解析token，如果是格式正确的token，允许查找数据库，并且继续搜索教务系统
        try {
            let decoded = jwt.verify(token, 'thefirstminappofvtmer');
            console.log(decoded)
            let openid = decoded.openid;
            //查找数据库中是否已经绑定
            var db = mongo.db("mongodb://localhost:27017/weGDUT");
            db.bind('weGDUT');
            var result = new Promise((resolve, reject) => {
                db.weGDUT.find({ openid: openid }).toArray(function (err, items) {
                    resolve(items)
                })
            })
            var users;
            result.then(function (value) {
                users = value[0]
                if (!users) {
                    res.send({ code: 505, message: 'No this user' })
                } else {
                    //找到该用户
                    //读取数据库
                    var db = mongo.db("mongodb://localhost:27017/monents");
                    db.bind('monents');
                    var monentsRes = new Promise((resolve, reject) => {
                        db.monents.find({ uuid: uuid }).toArray(function (err, items) {
                            resolve(items)
                        })
                    })
                    var db = mongo.db("mongodb://localhost:27017/comments");
                    db.bind('comments');
                    var commnetsRes = new Promise((resolve, reject) => {
                        db.comments.find({ uuid: uuid }).toArray(function (err, items) {
                            resolve(items)
                        })
                    })
                    monentsRes.then(function (value) {
                        var monentDetail = value[0]
                        if (monentDetail) {
                            console.log(monentDetail)
                            commnetsRes.then(function (commentDetail) {
                                monentDetail.comments = commentDetail
                                res.send({ code: 200, message: 'ok', data: monentDetail })
                            })
                        }else{
                            res.send({ code: 500, message: 'not found' })
                        }
                    })

                }
            })
        } catch (err) {
            res.send({ code: 401, message: 'token invid' })
        }
    } else {
        res.send({ code: 402, message: 'token or uuid is required' })
    }
}


function del(req, res, next) {
    var token = req.body.token
    var uuid = req.body.uuid

    console.log('content' + uuid)
    if (token && uuid) {
        //尝试是否可以解析token，如果是格式正确的token，允许查找数据库，并且继续搜索教务系统
        try {
            let decoded = jwt.verify(token, 'thefirstminappofvtmer');
            console.log(decoded)
            let openid = decoded.openid;
            //查找数据库中是否已经绑定
            var db = mongo.db("mongodb://localhost:27017/weGDUT");
            db.bind('weGDUT');
            var result = new Promise((resolve, reject) => {
                db.weGDUT.find({ openid: openid }).toArray(function (err, items) {
                    resolve(items)
                })
            })
            var users;
            result.then(function (value) {
                users = value[0]
                if (!users) {
                    res.send({ code: 505, message: 'No this user' })
                } else {
                    //找到该用户
                    //删除moments
                    db = mongo.db("mongodb://localhost:27017/monents");
                    db.bind('monents');
                    db.monents.remove({ uuid: uuid })
                    //删除comments
                    db = mongo.db("mongodb://localhost:27017/comments");
                    db.bind('comments');
                    db.comments.remove({ uuid: uuid })

                    res.send({ code: 200, message: 'ok,deleted' })
                }
            })
        } catch (err) {
            res.send({ code: 401, message: 'token invid' })
        }
    } else {
        res.send({ code: 402, message: 'token or uuid is required' })
    }
}


module.exports = { send, getAllMonents, sendComment, like, detail ,del, getPersonMonents};

